<?php
namespace app\mobile\service;

use think\facade\Db;
use think\facade\Config;

/**
 * 市级老板表
 * Class CityBossService
 *
 * @package app\admin\service
 */
class WechatpayService
{

    public function wechatXcxPay($array)
    {
        try {
            $appid = $array['appid'];//
            $mchid = $array['mchid'];;//商户id
            $xlid = $array['serial_number'];//证书序列号
            $time = time(); //时间戳
            $orderid = $array['order_sn'];//订单编号
            $noncestr = md5($orderid . $time . rand());//随机字符串，可以将订单编号存于此处
            $url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi';//生成预支序号所提交路径
            $urlarr = parse_url($url); //路径拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/jsapi]
            $data = array();
            $data['appid'] = $appid;
            $data['mchid'] = strval($mchid);
            $data['description'] = $array['title'];//商品描述
            $data['out_trade_no'] = $orderid;//订单编号
            $data['notify_url'] = $array['notify_url'];//回调接口，可以为空
            $data['amount']['total'] = intval( bcmul($array['price'],100));//金额 单位 分
            $data['amount']['currency'] = 'CNY';
            $data['payer']['openid'] = $array['openid'];//openid

            $jsonData = json_encode($data); //变为json格式
            $str = "POST" . "\n" . $urlarr['path'] . "\n" . $time . "\n" . $noncestr . "\n" . $jsonData . "\n";
            $signHead = $this->getPrivateSign($str,$array['pay_key']);
            $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $signHead);

            $header = array(
                'Content-Type:application/json; charset=UTF-8',
                'Accept:application/json',
                'User-Agent:*/*',
                'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token
            );
            $res = $this->httpRequest($url, $jsonData, $header);
            $dataArray = json_decode($res, true);

            if (isset($dataArray['prepay_id'])) {
                $prepayID = $dataArray['prepay_id'];
                $prepay = 'prepay_id=' . $prepayID;
                $str = $appid . "\n" . $time . "\n" . $noncestr . "\n" . $prepay . "\n";
                $signPay = $this->getPrivateSign($str,$array['pay_key']);
                $return = [
                    'paySign' => $signPay,
                    'nonceStr' => $noncestr,
                    'timeStamp' => $time,
                    'package' => $prepay,
                    'appid' => $appid,
                    'signType' => 'RSA'
                ];
            } else {
                return ['code' => 0, 'msg' => $dataArray['message']];
            }

        } catch (\Exception $exception) {
            return ['code' => 0, 'msg' => $exception->getMessage()];
        }
        return ['code' => 1, 'data' => $return];

    }
    public function mWechatXcxPay($array)
    {
        try {

            $appid =$array['sp_appid'];//
            $mchid = $array['sp_mchid'];;// 服务商户id
            $subMchid = $array['sub_mchid'];//
            $xlid = $array['serial_number'];//证书序列号
            $time = time(); //时间戳
            $orderid = $array['sn_order'];//订单编号
            $noncestr = md5($orderid . $time . rand());//随机字符串，可以将订单编号存于此处

            $url = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/jsapi";//生成预支序号所提交路径
            $urlarr = parse_url($url);
            $data = array();
            $data['sp_appid'] = $appid;
            $data['sp_mchid'] = strval($mchid);
            $data['sub_mchid'] = strval($subMchid);
            $data['description'] = $array['title'];//商品描述
            $data['out_trade_no'] = $orderid;//订单编号
            $data['notify_url'] = $array['notify_url'];//回调接口，可以为空
            $data['amount']['total'] = intval(bcmul($array['price'],100));//金额 单位 分
            $data['amount']['currency'] = 'CNY';
            $data['payer']['sp_openid'] = $array['openid'];//openid
            $jsonData = json_encode($data); //变为json格式
            $str = "POST" . "\n" . $urlarr['path'] . "\n" . $time . "\n" . $noncestr . "\n" . $jsonData . "\n";
            $signHead = $this->getPrivateSign($str,$array['pay_key']);
            $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $noncestr, $time, $xlid, $signHead);
            $header = array(
                'Content-Type:application/json; charset=UTF-8',
                'Accept:application/json',
                'User-Agent:*/*',
                'Authorization: WECHATPAY2-SHA256-RSA2048  '. $token
            );
            $res = $this->httpRequest($url, $jsonData, $header);

            $dataArray = json_decode($res, true);
            if (isset($dataArray['prepay_id'])) {
                $prepayID = $dataArray['prepay_id'];
                $prepay = 'prepay_id=' . $prepayID;
                $str = $appid . "\n" . $time . "\n" . $noncestr . "\n" . $prepay . "\n";
                $signPay = $this->getPrivateSign($str,$array['pay_key']);
                $return = [
                    'paySign' => $signPay,
                    'nonceStr' => $noncestr,
                    'timeStamp' => $time,
                    'package' => $prepay,
                    'appid' => $appid,
                    'signType' => 'RSA'
                ];
            } else {
                return ['code' => 0, 'msg' => $dataArray['message']];
            }

        } catch (\Exception $exception) {
            return ['code' => 0, 'msg' => $exception->getMessage()];
        }
        return ['code' => 1, 'data' => $return];


    }

//    public function wechatPay($array)
//    {
//        try {
//            $appid = $array['appid'];//
//            $mchid = $array['mchid'];;//商户id
//            $xlid = $array['serial_number'];//证书序列号
//            $time = time(); //时间戳
//            $orderid = $array['order_sn'];//订单编号
//            $noncestr = md5($orderid . $time . rand());//随机字符串，可以将订单编号存于此处
//            $url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/h5';//生成预支序号所提交路径
//            $urlarr = parse_url($url); //路径拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/jsapi]
//            $data = array();
//            $data['appid'] = $appid;
//            $data['mchid'] = strval($mchid);
//            $data['description'] = $array['title'];//商品描述
//            $data['out_trade_no'] = $orderid;//订单编号
//            $data['notify_url'] = $array['notify_url'];//回调接口，可以为空
//            $data['amount']['total'] = intval(bcmul($array['price'],100));//金额 单位 分
//            $data['scene_info']['payer_client_ip'] =$array['payer_client_ip'] ;//金额 单位 分
//            $data['scene_info']['h5_info']['type'] ='Wap' ;
//            $data['amount']['currency'] = 'CNY';
//           // $data['payer']['openid'] = $array['openid'];//openid
//            $jsonData = json_encode($data); //变为json格式
//            $str = "POST" . "\n" . $urlarr['path'] . "\n" . $time . "\n" . $noncestr . "\n" . $jsonData . "\n";
//            $signHead = $this->getPrivateSign($str,$array['pay_key']);
//            $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $signHead);
//
//            $header = array(
//                'Content-Type:application/json; charset=UTF-8',
//                'Accept:application/json',
//                'User-Agent:*/*',
//                'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token
//            );
//            $res = $this->httpRequest($url, $jsonData, $header);
//            $dataArray = json_decode($res, true);
//
//            if (isset($dataArray['h5_url'])) {
//                $return = [
//                    'h5_url' => $dataArray['h5_url'],
//                ];
//            } else {
//                return ['code' => 0, 'msg' => $dataArray['message']];
//            }
//
//        } catch (\Exception $exception) {
//            return ['code' => 0, 'msg' => $exception->getMessage()];
//        }
//        return ['code' => 1, 'data' => $return];
//
//    }
//    public function mWechatPay($array)
//    {
//        try {
//            $appid =$array['sp_appid'];//
//            $mchid = $array['sp_mchid'];;// 服务商户id
//            $subMchid = $array['sub_mchid'];//
//            $xlid = $array['serial_number'];//证书序列号
//            $time = time(); //时间戳
//            $orderid = $array['order_sn'];//订单编号
//            $noncestr = md5($orderid . $time . rand());//随机字符串，可以将订单编号存于此处
//            $url = 'https://api.mch.weixin.qq.com/v3/pay/partner/transactions/h5';//生成预支序号所提交路径
//            $urlarr = parse_url($url); //路径拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/jsapi]
//            $data = array();
//            $data['sp_appid'] = $appid;
//            $data['sp_mchid'] = strval($mchid);
//            $data['sub_mchid'] = strval($subMchid);
//            $data['description'] = $array['title'];//商品描述
//            $data['out_trade_no'] = $orderid;//订单编号
//            $data['notify_url'] = $array['notify_url'];//回调接口，可以为空
//            $data['amount']['total'] = intval(bcmul($array['price'],100));//金额 单位 分
//            $data['scene_info']['payer_client_ip'] =$array['payer_client_ip'] ;//金额 单位 分
//            $data['scene_info']['h5_info']['type'] ='Wap' ;
//            $data['amount']['currency'] = 'CNY';
//         //   $data['payer']['sp_openid'] =  $array['openid'];//openid
//            $jsonData = json_encode($data); //变为json格式
//            $str = "POST" . "\n" . $urlarr['path'] . "\n" . $time . "\n" . $noncestr . "\n" . $jsonData . "\n";
//            $signHead = $this->getPrivateSign($str,$array['pay_key']);
//            $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $signHead);
//
//            $header = array(
//                'Content-Type:application/json; charset=UTF-8',
//                'Accept:application/json',
//                'User-Agent:*/*',
//                'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token
//            );
//            $res = $this->httpRequest($url, $jsonData, $header);
//            $dataArray = json_decode($res, true);
//
//            if (isset($dataArray['h5_url'])) {
//                $return = [
//                    'h5_url' => $dataArray['h5_url'],
//                ];
//            } else {
//                return ['code' => 0, 'msg' => $dataArray['message']];
//            }
//
//        } catch (\Exception $exception) {
//            return ['code' => 0, 'msg' => $exception->getMessage()];
//        }
//        return ['code' => 1, 'data' => $return];
//
//
//    }
    function getPrivateSign($content ,$keyFile)
    {
        $binary_signature = "";
        $privateKey = file_get_contents($keyFile);//证书
        $algo = "sha256WithRSAEncryption";

        //将上传内容与api证书结合生成签名
        openssl_sign($content, $binary_signature, $privateKey, $algo);

        return base64_encode($binary_signature);
    }

    public function httpRequest($url, $data, $header)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在，如果出错则修改为0，默认为1
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//$header以array格式
        }

        $response = curl_exec($curl); // 执行操作

        if (curl_errno($curl)) {
            echo 'Error:' . curl_error($curl);//捕抓异常
        }

        curl_close($curl); // 关闭CURL会话
        return $response; // 返回数据，json格式
    }

    public  function getAccessToken($appid,$appSecret){


            $url_get = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" .$appid . "&secret=" . $appSecret;
            $data = $this->curlGet($url_get);
            $output = json_decode($data, true);
            if (!isset($output['access_token'])){
                throw new \Exception('接口调用凭据失败');
            }

        return $output['access_token'];
    }

    public function  curlGet($url)
{
    $ch = curl_init();
    $header = array();
    $header[] = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

    public function getwxacode($storeId,$appid,$appSecret){
        $accessToken = $this->getAccessToken($appid,$appSecret);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$accessToken;
        $path = 'pages/index/storeDetail';

        $params = [
            'page' => $path,
            // 'access_token' => $accessToken,
            'scene' => $storeId,
            'env_version' => 'release',
            'check_path' => false

        ];
        $data = $this->curlPost($url,json_encode($params));

       $result = json_decode($data);
       if (isset($result['errcode'])){
           return ['code'=> 0,'分享码获取失败'];
       }

        /*  var_dump($data);exit;*/
//        $base64_image ="data:image/jpeg;base64,".base64_encode( $data );
//
//
//        $cleanBase64 = str_replace('data:image/jpeg;base64,', '', $base64_image);
        $imageName = uniqid().'.png';
         $filePath =    '/uploads/store/' .  $imageName; // 临时文件路径

        file_put_contents(root_path().'public/'.$filePath, $data);

       // $imageUrl = '/path-to-your-temp-folder/' . $imageName; // 根
        return ['code'=> 1,'分享码获取失败','img' => $filePath];
      return $filePath;
    }

    function curlPost($url,$data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }



    public function refunds($array)
    {
//        try {

        $mchid = $array['mchid'];;//商户id

        $xlid = $array['serial_number'];//证书序列号
        $time = time(); //时间戳
        $orderid = $array['order_sn'];//订单编号
        $noncestr = md5($orderid . $time . rand());//随机字符串，可以将订单编号存于此处
        $url = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';//生成预支序号所提交路径
        $urlarr = parse_url($url);
        $data = array();
        $no = getPayNo('tuk');; //获取退款单号
        $data['out_trade_no'] = $orderid;//订单编号
        $data['out_refund_no'] = $no;//订单编号
        $data['amount']['total'] = intval( bcmul($array['price'],100));//金额 单位 分
        $data['amount']['refund'] = intval( bcmul($array['price'],100));//金额 单位 分

        $data['amount']['currency'] = 'CNY';
        $jsonData = json_encode($data); //变为json格式
        $str = "POST" . "\n" . $urlarr['path'] . "\n" . $time . "\n" . $noncestr . "\n" . $jsonData . "\n";
        $signHead = $this->getPrivateSign($str,$array['pay_key']);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"', $mchid, $xlid, $noncestr, $time, $signHead);
        $header = array(
            'Content-Type:application/json; charset=UTF-8',
            'Accept:application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 ' . $token
        );

        $res = $this->httpRequest($url, $jsonData, $header);
        $dataArray = json_decode($res, true);

            $dataArray = json_decode($res, true);
            if(isset($dataArray['code']) && $dataArray['code'] == 'INVALID_REQUEST'){
                return $dataArray['message'];
            }
            if (isset($dataArray['status']) && ($dataArray['status'] == 'PROCESSING' || $dataArray['status'] == 'SUCCESS')) {
                return '退款成功';
            } else {
                return '退款失败,请联系客服11';
            }
//        } catch (\Exception $exception) {
//            return '退款失败，请联系客服';
//        }

    }
    public function mRefunds($array)
    {
        try {
            $time = time(); //时间戳
            $xlid = $this->config['m_serial_number'];//证书序列号
            $orderid = $array['order_sn'];//订单编号
            $noncestr = md5($orderid . $time . rand());//随机字符串，可以将订单编号存于此处
            $payTotal = $array['price'] * 100;//
            $url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";//提交路径
            $urlarr = parse_url($url);
            $no = $this -> getRefundNo('r_'); //获取退款单号
            $data = array();
            $data['out_trade_no'] = $orderid;       //订单编号
            $data['out_refund_no'] = $no;           //商户退款单号
            $data['reason'] = '合伙人审核未通过';         //退款原因
            $mchid = $this->config['sp_mchid'];;          // 服务商户id
            $data['amount']['refund'] = (integer)$payTotal;//金额 单位 分
            $data['amount']['total'] = (integer)$payTotal;//金额 单位 分
            $data['amount']['currency'] = 'CNY';
            $jsonData = json_encode($data); //变为json格式
            $str = "POST" . "\n" . $urlarr['path'] . "\n" . $time . "\n" . $noncestr . "\n" . $jsonData . "\n";
            $signHead = $this->getPrivateSign($str,$array['pay_key']);
            $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $noncestr, $time, $xlid, $signHead);
            $header = array(
                'Content-Type:application/json; charset=UTF-8',
                'Accept:application/json',
                'User-Agent:*/*',
                'Authorization: WECHATPAY2-SHA256-RSA2048  '. $token
            );
            $res = $this->httpRequest($url, $jsonData, $header);
            $dataArray = json_decode($res, true);
            if(isset($dataArray['code']) && $dataArray['code'] == 'INVALID_REQUEST'){
                return $dataArray['message'];
            }
            if (isset($dataArray['status']) && ($dataArray['status'] == 'PROCESSING' || $dataArray['status'] == 'SUCCESS')) {
                return '退款成功';
            } else {
                return '退款失败,请联系客服';
            }
        } catch (\Exception $exception) {
            return '退款失败，请联系客服';
        }


    }


}


